package cn.tedu.dao.repository.impl;


import cn.tedu.dao.repository.IUserCacheRepository;
import common.pojo.PermissionPO;
import common.pojo.UserCachePO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Repository
public class UserCacheRepositoryImpl implements IUserCacheRepository {

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;


    @Override
    public UserCachePO getUserState(Long id) {
        return getUserCachePOByHashNoShared(id);
    }

    @Override
    public void deleteUserState(Long id) {
        //todo 通过用户id 删除用户信息, redis 对 key的删除,自己写
    }

    @Override
    public void renewal(Long userId) {
        String key = KEY_PREFIX_USER_STATE + userId;
        redisTemplate.expire(key,1L, TimeUnit.HOURS);
    }

    private UserCachePO getUserCachePOByHashNoShared(Long userId){
        HashOperations<String, Object, Object> hashOperations = redisTemplate.opsForHash();
        String key = KEY_PREFIX_USER_STATE + userId;
        //通过用户id获取redis中的信息 没有获取到
        //原因分析
        //1 存失败
        //2 key不对
        //3 过期
        Object enable = hashOperations.get(key, "enable");
        Object auth = hashOperations.get(key, "auth");
        //List<Object> enable1 = hashOperations.multiGet(key, Arrays.asList("enable", "auth"));
        UserCachePO userCachePO = new UserCachePO();
        //对象怎么转换为Integer
        //todo 恶心的转换
        if (enable != null) {
            userCachePO.setEnable(Integer.valueOf(String.valueOf(enable)));
        }else {
            return null;
        }
        if (auth != null) {
            List list  = (List)auth;
            List<PermissionPO> permissionPOS = new ArrayList<>();
            for (Object o : list) {
                PermissionPO permissionPO =  (PermissionPO)o;
                permissionPOS.add(permissionPO);
            }
            userCachePO.setPermissions(permissionPOS);
        }else{
            //有的用户是没有任何权限的
            //return null;
        }
        userCachePO.setUserId(userId);
        return userCachePO;
    }

    public static void main(String[] args) {
        Object obj = null;
        String s = String.valueOf(obj);
        System.out.println(s);
        //null的字符串是不能转换为Integer
        Integer integer = Integer.valueOf(s);
        System.out.println(integer);
    }
}
